package logic

import (
	"context"
	"encoding/json"
	"gitee.com/Cauchy_AQ/vxopen/model/mongodb"

	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/internal/svc"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/transform"

	"github.com/zeromicro/go-zero/core/logx"
)

type WsConnectionHandlerLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewWsConnectionHandlerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WsConnectionHandlerLogic {
	return &WsConnectionHandlerLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *WsConnectionHandlerLogic) WsConnectionHandler(in *transform.WsConnReq) (*transform.WsConnResp, error) {
	timestamp := in.Timestamp
	mongoClient := mongodb.GetMongoInstance(l.svcCtx.Config.ModelConfig)

	messages, err := mongoClient.ChatCol.FindManyByTimestamp(context.Background(), timestamp)
	if err != nil {
		return nil, err
	}
	data := make([][]byte, len(messages))
	for i := 0; i < len(messages); i++ {
		b, _ := json.Marshal(messages[i])
		data[i] = b
	}
	return &transform.WsConnResp{
		Message: data,
	}, nil
}
